package com.liumuxian.base.service.impl;


import com.liumuxian.base.dao.IntegralTypeDao;
import com.liumuxian.base.pojo.IntegralType;
import com.liumuxian.base.service.IntegralTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;
import util.VagueUtil;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;

@Service
@Transactional
public class IntegerTypeServiceImpl implements IntegralTypeService {
    @Autowired
    IntegralTypeDao integralTypeDao;
    @Autowired
    VagueUtil<IntegralType> vagueUtil;
    @Autowired
    IdWorker idWorker;
    @Override
    public void save(IntegralType integralType) {
        integralType.setId(idWorker.nextId()+"");
        integralType.setCreatdata(new Date());
        integralType.setUpdatedate(new Date());
        integralTypeDao.save(integralType);
    }

    @Override
    public IntegralType updatetopage(String id) {
        return integralTypeDao.getOne(id);
    }

    @Override
    public void updates(IntegralType integralType) {
        integralType.setUpdatedate(new Date());
        integralTypeDao.saveAndFlush(integralType);
    }

    @Override
    public Page<IntegralType> findAll(Integer pagesize, Integer pagenumber, IntegralType integralType)throws Exception {
        HashMap<String,Object> hm=new HashMap<>();
        Method[] sourceMethods = integralType.getClass().getMethods();
        for(int i=0;i<sourceMethods.length;i++){
            if(sourceMethods[i].getName().startsWith("get")){
                String lsName = sourceMethods[i].getName().substring(3);   // 属性
                Object loValue = sourceMethods[i].invoke(integralType, null);  // 值
                if(!lsName.toLowerCase().equals("class")){
                    hm.put(lsName.toLowerCase(),loValue);
                }
            }
        }
        Specification<IntegralType> specification = vagueUtil.createSpecification(hm);
        PageRequest pageRequest =  PageRequest.of(pagenumber-1, pagesize);
        return integralTypeDao.findAll(specification,pageRequest);
    }

    @Override
    public void deletes(String id) {
        integralTypeDao.deleteById(id);
    }
}
